<?php

namespace app\common\model\xiluedu;

use app\common\library\Auth;
use app\common\model\User;
use think\Db;
use think\Exception;
use think\Hook;
use think\Model;
use function fast\array_get;


class OfflineOrder extends Model
{
    // 表名
    protected $name = 'xiluedu_offline_order';

    protected $autoWriteTimestamp = 'int';

    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    protected $append = [
        'state',
        'state_text',
        'course_start_time_text',
        'course_end_time_text',
    ];

    public function user() {
        return $this->belongsTo(User::class, 'user_id')->setEagerlyType(0);
    }

    public function offlineCourse() {
        return $this->belongsTo('offlineCourse', 'course_id')->setEagerlyType(1);
    }

    public function getCourseStartTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['course_start_time']) ? $data['course_start_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i", $value) : $value;
    }

    public function getCourseEndTimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['course_end_time']) ? $data['course_end_time'] : '');
        return is_numeric($value) ? date("Y-m-d H:i", $value) : $value;
    }

    public function getStateAttr($value,$data){
        if($data['course_start_time'] > time()){
            return 1; //即将开始
        }else if($data['course_start_time'] < time()){
            return 2; //已经开始
        }else{
            return 0; //已经过期
        }
    }

    public function getStateTextAttr($value,$data){
        $state_attr = [1 => '未开始', 2 => '进行中', 3 => '已结束'];
        $state = $this->getAttr('state');
        return $state_attr[$state];
    }

    /**
     * 报名订单
     * @param $params
     * @return OfflineOrder
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function createOrder($params) {
        $offline_course_id = array_get($params,'offline_course_id');
        $username = array_get($params,'username');
        $mobile = array_get($params,'mobile');
        if(!$offline_course_id || !$username || !$mobile){
            throw new Exception("非法参数");
        }
        $offline_course = OfflineCourse::get($offline_course_id);
        if(!$offline_course || $offline_course->status == '0'){
            throw new Exception("课程不存在或已下架");
        }
        $auth = Auth::instance();
        #报名数据
        $data = [
            'platform'          =>  array_get($params,'platform','wxmini'),
            'user_id'           =>  $auth->id,
            'order_no'          =>  "B".date('YmdHis').mt_rand(10,9999),
            'pay_price'         =>  $offline_course->salesprice,
            'username'          =>  $username,
            'mobile'            =>  $mobile,
            'course_id'         =>  $offline_course_id,
            'course_name'       =>  $offline_course->name,
            'course_introduce'  =>  $offline_course->introduce,
            'course_image'      =>  $offline_course->thumb_image,
            'course_salesprice' =>  $offline_course->salesprice,
            'course_teacher_id' =>  $offline_course->teacher_id,
            'course_teacher_name'=>  $offline_course->teacher ? $offline_course->teacher->name : '',
            'course_content'    =>  $offline_course->content,
            'course_start_time' =>  $offline_course->start_time,
            'course_end_time'   =>  $offline_course->end_time,
            'course_address'    =>  $offline_course->address,
            'course_mobile'     =>  $offline_course->mobile,
            'ip'                =>  request()->ip()
        ];
        $offline_order = self::create($data);
        return $offline_order;
    }
    public static function lists($params){
        $auth = Auth::instance();
        $tab = array_get($params,'tab');
        $pagesize = array_get($params,'pagesize',10);
        $where['user_id'] = $auth->id;
        if($tab == 0){
            $where['pay_status'] = 0;
        }else if($tab == 1){
            $where['pay_status'] = 1;
            $where['refund_status'] = 0;
        }else if($tab == 2){
            #已退款
            $where['pay_status'] = 1;
            $where['refund_status'] = 3;
        }
        return static::field('wxconfig,transaction_id',true)
            ->where($where)
            ->order('paytime','desc')
            ->paginate($pagesize);
    }

    public static function detail($order_id){

        return self::where('id',$order_id)
            ->find();
    }

    /**
     * 线下课程
     * @param $params
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public static function offlineOrders($params){
        $auth = Auth::instance();
        $pagesize = array_get($params,'pagesize',10);
        return static::with(['offlineCourse'=>function($query){
            $query->withField(['id','name','address','start_time','end_time','thumb_image','total_count','enroll_count']);
        }])
            ->field('wxconfig,transaction_id',true)
            ->where('user_id',$auth->id)
            //->where('pay_status','1')
            ->order('paytime','desc')
            ->paginate($pagesize);
    }


    public static function pay_notify($order_no){
        $order = self::where('order_trade_no',$order_no)->find();
        if(!$order){
            throw new Exception('订单不存在');
        }
        if($order->pay_status == '1'){
            throw new Exception('订单已支付完毕');
        }
        $order->pay_status = '1';
        $order->paytime = time();
        $order->save();
        Hook::listen("xiluedu_offline_buy",$order);
        return $order;
    }
}
